package com.itheima.web;

import com.itheima.dao.impl.UserDaoImpl;
import com.itheima.domain.User;
import com.itheima.service.IUserService;
import com.itheima.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebServlet("/addUserServlet")
public class addUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {


        User user = new User();
        try {
            //利用BeanUtils工具类将请求体中的参数封装到user对象中
            BeanUtils.populate(user,request.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //调用业务层添加业务方法add方法
        IUserService service = new UserServiceImpl();
        //调用dao中的方法add方法
        int row = service.addUser(user);
        if (row>0) {
            //添加成功
            response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");
        }else{
            //添加失败
            response.getWriter().write("添加失败");
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doPost(request, response);
    }
}
